package com.liuheng.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liuheng.spzx.common.exception.CustomException;
import com.liuheng.spzx.feign.cart.CartFeignClient;
import com.liuheng.spzx.feign.product.ProductFeign;
import com.liuheng.spzx.feign.user.UserFeignClient;
import com.liuheng.spzx.model.dto.h5.OrderInfoDto;
import com.liuheng.spzx.model.entity.h5.CartInfo;
import com.liuheng.spzx.model.entity.order.OrderInfo;
import com.liuheng.spzx.model.entity.order.OrderItem;
import com.liuheng.spzx.model.entity.order.OrderLog;
import com.liuheng.spzx.model.entity.product.ProductSku;
import com.liuheng.spzx.model.entity.user.UserAddress;
import com.liuheng.spzx.model.entity.user.UserInfo;
import com.liuheng.spzx.model.vo.common.ResultCodeEnum;
import com.liuheng.spzx.model.vo.h5.TradeVo;
import com.liuheng.spzx.order.config.MyPage;
import com.liuheng.spzx.order.mapper.OrderInfoMapper;
import com.liuheng.spzx.order.mapper.OrderItemMapper;
import com.liuheng.spzx.order.mapper.OrderLogMapper;
import com.liuheng.spzx.order.service.OrderInfoService;
import com.liuheng.util.AuthContextUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper,OrderInfo> implements OrderInfoService {
    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private ProductFeign productFeign;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;
    @Override
    public TradeVo getTrade() {
        List<CartInfo> cartInfos = cartFeignClient.getAllChecked();
        TradeVo tradeVo = new TradeVo();
        List<OrderItem> orderItemList=new ArrayList<>();
        for (CartInfo cartInfo : cartInfos) {
            OrderItem orderItem = new OrderItem();
            orderItem.setSkuId(cartInfo.getSkuId());
            orderItem.setSkuName(cartInfo.getSkuName());
            orderItem.setSkuNum(cartInfo.getSkuNum());
            orderItem.setSkuPrice(cartInfo.getCartPrice());
            orderItem.setThumbImg(cartInfo.getImgUrl());
            orderItemList.add(orderItem);
        }
        BigDecimal totalAmount = new BigDecimal(0);
        for(OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
         tradeVo.setTotalAmount(totalAmount);
         tradeVo.setOrderItemList(orderItemList);
        return tradeVo;
    }

    @Override
    public Long submitOrder(OrderInfoDto orderInfoDto) {
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        List<OrderItem> orderItemList = orderInfoDto.getOrderItemList();
        if(orderItemList==null){
            throw new CustomException(ResultCodeEnum.DATA_ERROR);
        }
        for (OrderItem orderItem : orderItemList) {
            ProductSku productSku = productFeign.getBySkuId(orderItem.getSkuId());
            if (productSku == null) {
                throw new CustomException(ResultCodeEnum.DATA_ERROR);
            }
            if (productSku.getStockNum().intValue() < orderItem.getSkuNum().intValue()) {
                throw new CustomException(ResultCodeEnum.STOCK_LESS);
            }
        }
            OrderInfo orderInfo = new OrderInfo();
            //订单编号
            orderInfo.setOrderNo(String.valueOf(System.currentTimeMillis()));
            //用户id
            orderInfo.setUserId(userInfo.getId());
            //用户昵称
            orderInfo.setNickName(userInfo.getNickName());
            //用户收货地址信息
            UserAddress userAddress = userFeignClient.getUserAddress(orderInfoDto.getUserAddressId());
            orderInfo.setReceiverAddress(userAddress.getFullAddress());
            orderInfo.setReceiverName(userAddress.getName());
            orderInfo.setReceiverPhone(userAddress.getPhone());
            orderInfo.setReceiverTagName(userAddress.getTagName());
            orderInfo.setReceiverProvince(userAddress.getProvinceCode());
            orderInfo.setReceiverCity(userAddress.getCityCode());
            orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
            BigDecimal totalAmount = new BigDecimal(0);
            for (OrderItem orderItem : orderItemList) {
                totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
            }
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setCouponAmount(new BigDecimal(0));
        orderInfo.setOriginalTotalAmount(totalAmount);
        orderInfo.setFeightFee(orderInfoDto.getFeightFee());
        orderInfo.setPayType(2);
        orderInfo.setOrderStatus(0);
        orderInfoMapper.insert(orderInfo);
        //保存订单明细
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
            orderItemMapper.insert(orderItem);
        }

        //记录日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(0);
        orderLog.setNote("提交订单");
        orderLogMapper.insert(orderLog);
       //删除购物车redis中选中的商品数据
        cartFeignClient.deleteChecked();

        return orderInfo.getId();
    }

    @Override
    public TradeVo buy(Long skuId) {
        ProductSku bySkuId = productFeign.getBySkuId(skuId);
        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(skuId);
        orderItem.setSkuName(bySkuId.getSkuName());
        orderItem.setSkuNum(1);
        orderItem.setSkuPrice(bySkuId.getSalePrice());
        orderItem.setThumbImg(bySkuId.getThumbImg());
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(bySkuId.getSalePrice());
        List<OrderItem> orderItems = new ArrayList<>();
        orderItems.add(orderItem);
        tradeVo.setOrderItemList(orderItems);
        return tradeVo;
    }

    @Override
    public Page<OrderInfo> findpage(Page<OrderInfo> page1, Integer orderStatus) {
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        Long userId = userInfo.getId();
        LambdaQueryWrapper<OrderInfo> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(OrderInfo::getUserId,userId).eq(orderStatus!=null,OrderInfo::getOrderStatus,orderStatus);
        Page<OrderInfo> page = orderInfoMapper.selectPage(page1, wrapper1);
        for (OrderInfo orderInfo : page.getRecords()) {
            LambdaQueryWrapper<OrderItem> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderItem::getOrderId,orderInfo.getId());
            orderInfo.setOrderItemList(orderItemMapper.selectList(wrapper));
        }
        MyPage myPage = new MyPage();
        BeanUtils.copyProperties(page,myPage);
        myPage.setList(page.getRecords());
        return myPage;
    }

    @Override
    public void updateOrderStatus(String orderNo, Integer orderStatus) {
        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderInfo::getOrderNo,orderNo);
        OrderInfo orderInfo = orderInfoMapper.selectOne(wrapper);
        orderInfo.setOrderStatus(1);
        orderInfo.setPayType(orderStatus);
        orderInfo.setPaymentTime(new Date());
        orderInfoMapper.updateById(orderInfo);
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(1);
        orderLog.setNote("支付宝支付成功");
        orderLogMapper.insert(orderLog);
    }


}
